package java8.atguigu.lu.l01;

import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program lambda
 * @description:
 * @author: zhanglu
 * @create: 2019-05-26 10:42:00
 */
public class LuTest {

    List<Employee> employeeList = Arrays.asList(
            new Employee("张1",20,100),
            new Employee("张2", 21, 101),
            new Employee("张3", 22, 102),
            new Employee("张4", 23, 103),
            new Employee("张5", 24, 104),
            new Employee("张6", 25, 105)
    );

    /**
     * 优化方式一：策略模式
     */
    @Test
    public void test01(){
        List<Employee> employees = function(employeeList, new Filter01());
        for(Employee employee : employees){
            System.out.println(employee);
        }

        System.out.println("--------------------------------------");

        List<Employee> employees2 = function(employeeList, new Filter02());
        for(Employee employee : employees2){
            System.out.println(employee);
        }
    }


    /**
     * 优化方式二：匿名内部类
     */
    @Test
    public void test02(){
        List<Employee> employees = function(employeeList, new MyPredicate<Employee>() {
            @Override
            public boolean test(Employee employee) {
                return employee.getCount() > 104;
            }
        });
        for(Employee employee : employees){
            System.out.println(employee);
        }
    }

    /**
     * 优化方式三：lambda表达式
     */
    @Test
    public void test03(){
        List<Employee> employees = function(employeeList, (e) -> e.getAge() >= 23);
        employees.stream().forEach(System.out::println);
    }

    /**
     * 优化方式四：
     */
    @Test
    public void test04(){
        //过滤 转成 集合
        Object o = (Object) employeeList.stream().filter((e) -> e.getAge() >= 22).collect(Collectors.toList());

        //过滤 转成 map
        Object o2 = (Object) employeeList.stream().filter((e) -> e.getAge() >= 22).collect(Collectors.toMap(Employee::getAge, Employee -> Employee));

        System.out.println("1111");

        //过滤输出打印
        employeeList.stream().filter((e) -> e.getAge() >= 22).forEach(System.out::println);

        employeeList.stream().filter((e) -> e.getAge() > 22).limit(2).forEach(System.out::println);

        employeeList.stream().filter((e) -> e.getAge() > 23).map(Employee::getName).forEach(System.out::println);

    }



    public List<Employee> function(List<Employee> list, MyPredicate<Employee> predicate){
        List<Employee> employees = new ArrayList<>();
        for(Employee l : list){
            if(predicate.test(l)){
                employees.add(l);
            }
        }
        return employees;
    }

}
